package com.dg.redisson.locker;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonDistributedLocker implements DistributedLocker{

    //RedissonClient已经由配置类生成，这里自动装配即可
    @Autowired
    private RedissonClient redissonClient;

    /**
     * @Author dabing9
     * @Description 获取锁，如果拿不到一直等待，知道那道锁为止
     * @Date 2019/5/22 0022 下午 17:02
     * @Param [lockKey]
     * @return
     **/
    public RLock lock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
        return rLock;
    }

    /**
     * @Author dabing9
     * @Description 获取锁，并设置加锁时间
     * @Date 2019/5/22 0022 下午 18:05
     * @Param lockKey
     * @Param timeout 加锁时间，单位秒
     * @return
     **/
    public RLock lock(String lockKey, long timeout) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(timeout, TimeUnit.SECONDS);
        return rLock;
    }

    /**
     * @Author dabing9
     * @Description 获取锁，并设置加锁时间
     * @Date 2019/5/22 0022 下午 18:08
     * @Param lockKey
     * @Param unit 加锁时间单位
     * @Param timeout 加锁时间
     * @return
     **/
    public RLock lock(String lockKey, TimeUnit unit, long timeout) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(timeout, unit);
        return rLock;
    }

    /**
     * @Author dabing9
     * @Description 拿到锁返回true,并设置锁时间，等待waitTime还拿不到锁，返回false
     * @Date 2019/5/22 0022 下午 18:11
     * @Param lockKey
     * @Param unit 时间单位
     * @Param waitTime 等待时间
     * @Param leaseTime 设置锁时间
     * @return
     **/
    public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            return rLock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Author dabing9
     * @Description 解锁
     * @Date 2019/5/22 0022 下午 18:14
     * @Param lockKey
     * @return
     **/
    public void unlock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.unlock();
        System.err.println(Thread.currentThread().getName() + " 解锁，lockKey: " + lockKey);
    }
    
    /**
     * @Author dabing9
     * @Description 解锁
     * @Date 2019/5/22 0022 下午 18:15
     * @Param lock
     * @return 
     **/
    public void unlock(RLock lock) {
        lock.unlock();
    }
}